package com.yst.shader.feature.shimmer;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.yst.shader.widget.UriImageView;

import static android.graphics.Canvas.ALL_SAVE_FLAG;

/**
 * @author: YSTEN
 * @date: 2020/8/17 23:03
 */
public class ShimmerView extends UriImageView {
    protected final Paint mContentPaint = new Paint();
    protected ShimmerDrawable mShimmerDrawable = new ShimmerDrawable();
    protected boolean enableShimmer = false;

    public ShimmerView(Context context) {
        super(context);
        init(context, null);
    }

    public ShimmerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public ShimmerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }


    private void init(Context context, @Nullable AttributeSet attrs) {
        setWillNotDraw(false);
        mShimmerDrawable.setCallback(this);
        // setLayerType(LAYER_TYPE_HARDWARE, mContentPaint);
    }

    public void shimmer() {
        mShimmerDrawable.updateDrawable();
    }

    public void startShimmer() {
        if (enableShimmer) {
            mShimmerDrawable.startShimmer();
        }
    }

    public void stopShimmer() {
        mShimmerDrawable.stopShimmer();
    }

    public boolean isShimmerStarted() {
        return mShimmerDrawable.isShimmerStarted();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mShimmerDrawable.setBounds(0, 0, getWidth(), getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (enableShimmer) {
            int layer = canvas.saveLayer(
                    0f, 0f, getWidth(), getHeight(),
                    null, ALL_SAVE_FLAG
            );
            super.onDraw(canvas);
//        mContentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST));
            mShimmerDrawable.draw(canvas);
//        mContentPaint.setXfermode(null);
            canvas.restoreToCount(layer);
        } else {
            super.onDraw(canvas);
        }
    }

    @Override
    protected boolean verifyDrawable(@NonNull Drawable who) {
        return super.verifyDrawable(who) || who == mShimmerDrawable;
    }
}
